package com.gome.gop.common;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;
/**
 * 
 * @ClassName: JaxbUtil 
 * @Description: xml格式化工具
 * @author  chengcheng 1294480405@qq.com
 * @date 2018年5月28日 下午4:29:22
 */
public class JaxbUtil {

	private static Logger logger = Logger.getLogger(JaxbUtil.class);
			
	private static Map<Class<?>, JAXBContext> jaxbContextMap = new HashMap<Class<?>, JAXBContext>();
	private static Map<Class<?>, Marshaller>  marshallerMap = new HashMap<Class<?>, Marshaller>();
	private static Map<Class<?>, Unmarshaller>  unmarshallerMap = new HashMap<Class<?>, Unmarshaller>();
	
	private static void init(Class<?> clazz){
		try {
			if(!jaxbContextMap.containsKey(clazz)){
				jaxbContextMap.put(clazz, JAXBContext.newInstance(clazz));
				marshallerMap.put(clazz, jaxbContextMap.get(clazz).createMarshaller());
				unmarshallerMap.put(clazz, jaxbContextMap.get(clazz).createUnmarshaller());
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}
	private static Marshaller getMarshaller(Class<?> clazz){
		init(clazz);
		return marshallerMap.get(clazz);
	}
	private static Unmarshaller getUnmarshaller(Class<?> clazz){
		init(clazz);
		return unmarshallerMap.get(clazz);
	}
	public static String marshal(Object bean) throws JAXBException{
		StringWriter writer = new StringWriter();
//		getMarshaller(bean.getClass()).marshal(bean, writer);
		Marshaller m = getMarshaller(bean.getClass());
		synchronized (m) {
			m.marshal(bean, writer);
		}
		return writer.toString();
	}
	@SuppressWarnings("unchecked")
    public static <T> T unmarshal(String xml, Class<T> clazz) throws JAXBException{
		Unmarshaller um = getUnmarshaller(clazz);
		synchronized (um) {
			return (T) um.unmarshal(new StringReader(xml));
		}
	}
	
}
